package com.zlj.jdbc.servlet;

import java.io.IOException;
import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 *  使用JNDI来获取服务器配置的资源
 */
@WebServlet("/JdbcJNDIServlet")
public class JdbcJNDIServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			//创建JNDI上下文对象
			Context ctx = new InitialContext();
            //查询资源入口
//			Context envCtx = (Context)ctx.lookup("java:comp/env");
			//二次查询，找到资源对象
//			DataSource dataSource = (DataSource)envCtx.lookup("jdbc/dataSource");
			DataSource dataSource = (DataSource)ctx.lookup("java:comp/env/jdbc/dataSource");
			Connection conn = dataSource.getConnection();
			System.out.println(conn);
			conn.close(); 
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
